import store from '@/store'
import base from '@/common/baseUrl'
import Vue from 'vue'
import http from '@/common/http.js';
// import {
// 	getjuris
// } from '@/common/jurisdiction.js'
// import {
// 	getjuris
// } from '@/common/jurisdiction'
const formatTime = date => {
	var date = new Date(date)
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()
	var daytime = [year, month, day].map(formatNumber).join('/');
	var hourtime = [hour, minute, second].map(formatNumber).join(':')
	var time = {
		daytime: daytime,
		hourtime: hourtime
	}
	return time
}
const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}
const compressimg = (img) => {
	if (img) {
		var a = img.split('#');
		return a[0] + '?imageView/2/w/800'
	} else {
		return null
	}
}
const getQueryVariable = (variable, query) => {
	// var query = window.location.search.substring(1);
	if (query.indexOf('?') > -1) {
		var query = query.split('?');
		var vars = query[1].split("&");
		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split("=");
			if (pair[0] == variable) {
				return pair[1];
			}
		}
	} else {
		if (query.indexOf('&') > -1) {
			var vars = query.split("&");
			for (var i = 0; i < vars.length; i++) {
				var pair = vars[i].split("=");
				if (pair[0] == variable) {
					return pair[1];
				}
			}
		} else {
			if (query.indexOf('=') > -1) {
				var pair = query.split("=");
				if (pair[0] == variable) {
					return pair[1];
				}
			}
		}
	}
	return (false);
}
//乘法
const accMul = (arg1, arg2) => {
	var m = 0,
		s1 = arg1.toString(),
		s2 = arg2.toString();
	try {
		if (s1.split(".")[1] != undefined) m += s1.split(".")[1].length
	} catch (e) {}
	try {
		if (s2.split(".")[1] != undefined) m += s2.split(".")[1].length
	} catch (e) {}
	return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}
//浮点数除法运算  
const accDiv = (arg1, arg2) => {
	var r1 = 0,
		r2 = 0,
		m, s1 = arg1.toString(),
		s2 = arg2.toString();
	try {
		if (s1.split(".")[1] != undefined) r1 = s1.split(".")[1].length;
	} catch (e) {}
	try {
		if (s2.split(".")[1] != undefined) r2 = s2.split(".")[1].length;
	} catch (e) {}
	m = Math.pow(10, Math.max(r1, r2));
	return (accMul(arg1, m)) / (accMul(arg2, m));
}
//加法
const accAdd = (arg1, arg2) => {
	var r1 = 0,
		r2 = 0,
		m, s1 = arg1.toString(),
		s2 = arg2.toString();
	try {
		if (s1.split(".")[1] != undefined) r1 = s1.split(".")[1].length;
	} catch (e) {}
	try {
		if (s2.split(".")[1] != undefined) r2 = s2.split(".")[1].length;
	} catch (e) {}
	m = Math.pow(10, Math.max(r1, r2));
	return (accMul(arg1, m) + accMul(arg2, m)) / m;
}
// 减法
const Subtr = (arg1, arg2) => {
	var r1 = 0,
		r2 = 0,
		m, n, s1 = arg1.toString(),
		s2 = arg2.toString();
	try {
		if (s1.split(".")[1] != undefined) r1 = s1.split(".")[1].length;
	} catch (e) {}
	try {
		if (s2.split(".")[1] != undefined) r2 = s2.split(".")[1].length;
	} catch (e) {}
	m = Math.pow(10, Math.max(r1, r2));
	//last modify by deeka
	//动态控制精度长度
	n = (r1 >= r2) ? r1 : r2;
	return (accMul(arg1, m) - accMul(arg2, m)) / m;
}
const dataURLtoBlob = (dataurl) => {
	var arr = dataurl.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}
const downImg = (url) => {
	// 创建a标签 并设置其相关属性，最后触发其点击事件
	let a = document.createElement("a")
	let clickEvent = document.createEvent("MouseEvents");
	a.setAttribute("href", url)
	a.setAttribute("download", 'codeImg')
	a.setAttribute("target", '_blank')
	clickEvent.initEvent('click', true, true)
	a.dispatchEvent(clickEvent);
}
const convertCanvasToImg = (canvas) => {
	// canvas转base64 转 blob
	var myBlob = dataURLtoBlob(canvas)
	// blob转URL对象
	myUrl = URL.createObjectURL(myBlob)
	// 创建a标签，下载图片
	downImg(myUrl)
}
const toSaveImage = (path) => {
	// #ifdef H5
	uni.showToast({
		title: '长按保存图片',
		icon: 'none'
	})
	return false
	// #endif
	uni.saveImageToPhotosAlbum({
		filePath: path,
		success: () => {
			uni.showToast({
				title: '保存成功',
				icon: 'none'
			})
		},
		fail: function(err) {
			console.log(err)
			if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg ===
				"saveImageToPhotosAlbum:fail auth deny" || err.errMsg ===
				'saveImageToPhotosAlbum:fail authorize no response') {
				wx.showModal({
					title: '提示',
					content: '需要您授权保存相册',
					showCancel: false,
					success: modalSuccess => {
						wx.openSetting({
							success(settingdata) {
								console.log("settingdata", settingdata)
								if (settingdata.authSetting[
										'scope.writePhotosAlbum']) {
									wx.showModal({
										title: '提示',
										content: '获取权限成功,再次点击图片即可保存',
										showCancel: false,
									})
								} else {
									wx.showModal({
										title: '提示',
										content: '获取权限失败，将无法保存到相册哦~',
										showCancel: false,
									})
								}
							},
							fail(failData) {
								console.log("failData", failData)
							},
							complete(finishData) {
								console.log("finishData", finishData)
							}
						})
					}
				})
			}
		},
	})
}
const statuslist = [{
	value: '待支付',
	status: 1,
	selfvalue: '待支付'
}, {
	value: '待发货',
	status: 2,
	selfvalue: '待核销'
}, {
	value: '已发货',
	status: 3,
	selfvalue: '已发货'
}, {
	value: '已完结',
	status: 4,
	selfvalue: '已完结'
}, {
	value: '已评价',
	status: 5,
	selfvalue: '已评价'
}, {
	value: '删除',
	status: 6,
	selfvalue: '删除'
}, {
	value: '部分发货',
	status: 7,
	selfvalue: '部分发货'
}, {
	value: '已收货',
	status: 8,
	selfvalue: '已收货'
}, {
	value: '部分收货',
	status: 9,
	selfvalue: '部分收货'
}, {
	value: '维权中',
	status: 10,
	selfvalue: '维权中'
}, {
	value: '维权完成',
	status: 11,
	selfvalue: '维权完成'
}, {
	value: '已关闭',
	status: 12,
	selfvalue: '已关闭'
}, ]
const p_statuslist = [{
	value: '待发货',
	status: '12',
	selfvalue: '待发货'
}, {
	value: '待收货',
	status: '22',
	selfvalue: '待核销'
}, {
	value: '已收货',
	status: '32',
	selfvalue: '已收货'
}, {
	value: '已关闭',
	status: '42',
	selfvalue: '已关闭'
}, ]
const z_statuslist = [{
	value: '待发货',
	status: 1,
	selfvalue: '待发货'
}, {
	value: '待收货',
	status: 2,
	selfvalue: '待核销'
}, {
	value: '已收货',
	status: 3,
	selfvalue: '已收货'
}, {
	value: '已关闭',
	status: 4,
	selfvalue: '已关闭'
}, ]
const getstatustext = (status, type, m_type, suppdata) => {
	var list = JSON.parse(JSON.stringify(statuslist))
	if (m_type == 2) {
		list = JSON.parse(JSON.stringify(p_statuslist))
	}
	if (m_type == 3) {
		list = JSON.parse(JSON.stringify(z_statuslist))
	}
	// 1 - 待支付2 - 待发货3 - 已发货4 - 已完结5 - 已评价6 - 删除7 - 部分发货8 - 已收货9 - 部分收货
	let data = list.filter(a => {
		return status == a.status
	})
	if (status == 2 && suppdata && suppdata.groupstatus == 1) {
		data[0].selfvalue = '未成团'
		data[0].value = '未成团'
	}
	if (status == 2 && suppdata && suppdata.groupstatus == 2) {
		data[0].selfvalue = '待核销'
		data[0].value = '待发货'
	}
	if (suppdata && suppdata.groupstatus == 11) {
		data[0].selfvalue = '成团失败'
		data[0].value = '成团失败'
	}
	if (data.length == 1) {
		if (type == 2) {
			return data[0].selfvalue
		} else {
			return data[0].value
		}
	} else {
		return ''
	}
}
//公众号微信支付 
export const wxPublicPay = (payInfo, callback) => {
	let wxConfigObj = {
		appId: payInfo.appId,
		timeStamp: payInfo.timeStamp,
		nonceStr: payInfo.nonceStr,
		package: payInfo.package,
		signType: payInfo.signType,
		paySign: payInfo.paySign
	};

	function onBridgeReady() {
		window.WeixinJSBridge.invoke("getBrandWCPayRequest", wxConfigObj, function(res) {
			if (res.err_msg == "get_brand_wcpay_request:ok") {
				callback && callback(res);
			} else // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
				if (res.err_msg == "get_brand_wcpay_request:cancel") {
					// common.loadWarn('支付遇到问题，您取消了支付');
				} else
			if (res.err_msg == "get_brand_wcpay_request:fail") {
				// common.myConfirm('支付遇到问题,您可能需要重新登录', '', function () {
				//   obj.wxLoginOAuth();
				// });
			}
		});
	}
	if (typeof window.WeixinJSBridge == "undefined") {
		if (document.addEventListener) {
			document.addEventListener("WeixinJSBridgeReady", onBridgeReady, false);
		} else if (document.attachEvent) {
			document.attachEvent("WeixinJSBridgeReady", onBridgeReady);
			document.attachEvent("onWeixinJSBridgeReady", onBridgeReady);
		}
	} else {
		onBridgeReady();
	}
};
export const getCookie = (name) => {
	var strcookie = document.cookie; //获取cookie字符串
	var arrcookie = strcookie.split("; "); //分割
	//遍历匹配
	for (var i = 0; i < arrcookie.length; i++) {
		var arr = arrcookie[i].split("=");
		if (arr[0] == name) {
			return arr[1];
		}
	}
	return "";
}
//判断登录
export const judgeLogin = (callback, successback) => {
	let token = uni.getStorageSync('token')
	if (!token) {
		callback()
	} else {
		if (successback) {
			successback()
		}
	}
}
export const uniCopy = ({
	content,
	success,
	error
}) => {
	if (!content) return error('复制的内容不能为空 !')
	content = typeof content === 'string' ? content : content.toString() // 复制内容，必须字符串，数字需要转换为字符串
	/**
	 * 小程序端 和 app端的复制逻辑
	 */
	//#ifndef H5
	uni.setClipboardData({
		data: content,
		success: function() {
			success("复制成功~")
			console.log('success');
		},
		fail: function() {
			success("复制失败~")
		}
	});
	//#endif
	/**
	 * H5端的复制逻辑
	 */
	// #ifdef H5
	if (!document.queryCommandSupported('copy')) { //为了兼容有些浏览器 queryCommandSupported 的判断
		// 不支持
		error('浏览器不支持')
	}
	let textarea = document.createElement("textarea")
	textarea.value = content
	textarea.readOnly = "readOnly"
	document.body.appendChild(textarea)
	textarea.select() // 选择对象
	textarea.setSelectionRange(0, content.length) //核心
	let result = document.execCommand("copy") // 执行浏览器复制命令
	if (result) {
		success("复制成功~")
	} else {
		error("复制失败，请检查h5中调用该方法的方式，是不是用户点击的方式调用的，如果不是请改为用户点击的方式触发该方法，因为h5中安全性，不能js直接调用！")
	}
	textarea.remove()
	// #endif
}
export const onInput = (el, ele, binding, vnode) => {


	function handle() {
		let val = ele.value
		// modifiers为修饰符对象，传入了float，则其float属性为true
		if (binding.modifiers.float) {
			// 清除"数字"和"."以外的字符
			val = val.replace(/[^\d.]/g, '')
			// 只保留第一个, 清除多余的
			val = val.replace(/\.{2,}/g, '.')
			// 第一个字符如果是.号，则补充前缀0
			val = val.replace(/^\./g, '0.')
			if (typeof binding.value !== 'undefined') {
				// 期望保留的最大小数位数
				let pointKeep = 0
				if (typeof binding.value === 'string' || typeof binding.value === 'number') {
					pointKeep = parseInt(binding.value)
				}
				if (!isNaN(pointKeep)) {
					if (!Number.isInteger(pointKeep) || pointKeep < 0) {
						pointKeep = 0
					}
					const str = '^(\\d+)\\.(\\d\{' + pointKeep + '}).*$'
					const reg = new RegExp(str)
					if (pointKeep === 0) {
						// 不需要小数点
						val = val.replace(reg, '$1')
					} else {
						// 通过正则保留小数点后指定的位数
						val = val.replace(reg, '$1.$2')
					}
				}
			} else {
				val = ele.value.replace(/[^\d]/g, '')
			}
			ele.value = val
			if (vnode.componentInstance) {
				vnode.componentInstance.$emit('input', ele.value)
			} else {
				vnode.elm.dispatchEvent(new CustomEvent('input', ele.value))
			}
		}
	}
	return handle
}
//获取图片地址
export const getimgurl = (url, type) => {
	if (url) {
		if (url.indexOf('http') > -1) {
			return url
		} else {
			if (url.indexOf('/') == 0) {
				url = url.slice(0)
			}
			if (type == "1") {
				return base.imgUrl + '/' + url
			} else {
				if (store.state.oss) {
					return store.state.oss + '/' + url
					// var endpoint;
					// var bucket;
					// if (store.state.oss.is_open == 1) {
					// 	endpoint = store.state.oss.ali.endpoint;
					// 	bucket = store.state.oss.ali.bucket;
					// 	let burl = endpoint.replace('https://', 'https://' + bucket + '.')
					// 	return burl + url
					// } else {
					// 	endpoint = store.state.oss.qcloud.endpoint;
					// 	let burl = endpoint
					// 	return burl + '/' + url
					// }
				} else {
					return base.imgUrl + '/' + url
				}
			}
		}
	} else {
		return ''
	}
}
export const geturl = (url, type) => {
	if (store.state.oss) {
		return store.state.oss
		// var endpoint;
		// var bucket;
		// if (store.state.oss.is_open == 1) {
		// 	endpoint = store.state.oss.ali.endpoint;
		// 	bucket = store.state.oss.ali.bucket;
		// 	let burl = endpoint.replace('https://', 'https://' + bucket + '.')
		// 	return burl 
		// } else {
		// 	endpoint = store.state.oss.qcloud.endpoint;
		// 	// bucket = store.state.oss.qcloud.bucket;
		// 	let burl = endpoint
		// 	return burl 
		// }
	} else {
		return url
	}
}
export const changeloading = (val) => {
	store.commit('setloading', val);
}
// 解码
export const decodeUnicode = (str) => {
	str = str.replace(/\\/g, "%");
	//转换中文
	str = unescape(str);
	//将其他受影响的转换回原来
	str = str.replace(/%/g, "\\");
	//对网址的链接进行处理
	str = str.replace(/\\/g, "");
	// 	return price.sell_price
	return str;
}
export const getlevel = (level, list) => {
	// return {price:1}
	let data = {}
	let i = list.findIndex(_ => _.level == level);
	if (i > -1 && list[i].price > 0) {
		data = list[i];
	} else {
		level -= 1;
		if (level > 1) {
			data = getlevel(level, list)
		}
	}
	return data
}
export const getprice = (data) => {
	if (store.state.memberLevel) {
		if (store.state.memberLevel.is_open && store.state.memberLevel.is_price == 1) {
			if (!store.state.userInfo.level) {
				return 0
			}
		}
		var level = 0
		if (store.state.userInfo) {
			level = store.state.userInfo.level || 1
		}
		let price = 0
		if (data.level_price) {
			let l_price = JSON.parse(data.level_price);
			if (l_price.type == 1) {
				let m_price = getlevel(level, l_price.price)
				if (m_price.type == 1) {
					price = m_price.price
				} else if (m_price.type == 2) {
					price = accMul(m_price.price, data.sell_price) / 10
				}
				return Number(price).toFixed(2)
			} else if (l_price.type == 2) {
				if (store.state.leveldata) {
					price = accMul(store.state.leveldata.discount, data.sell_price) / 10
					return Number(price).toFixed(2)
				} else {
					return 0
				}
			} else {
				return 0
			}
		} else {
			return data.now_level_price
		}
	} else {
		return 0
	}
}
export const getminprice = (list, type) => {
	if (store.state.memberLevel) {
		if (store.state.memberLevel.is_open && store.state.memberLevel.is_price == 1) {
			if (!store.state.userInfo.level) {
				return 0
			}
		}
		let price = 0;
		let level = 0
		if (store.state.userInfo) {
			level = store.state.userInfo.level || 1
		}
		if (!Array.isArray(list)) {
			return 0
		}
		for (var i = 0; i < list.length; i++) {
			let a = list[i]
			let data = a
			if (type == 1) {} else {
				data = a.skuInventory
			}
			if (data.level_price) {
				let level_price = JSON.parse(data.level_price);
				if (level_price.type == 1) {
					var z_price = level_price.price;
					let m_price = getlevel(level, z_price)
					let l_price = 0;
					if (m_price.type == 1) {
						l_price = m_price.price
					} else if (m_price.type == 2) {
						l_price = accMul(m_price.price, data.sell_price) / 10
					}
					if (price == 0) {
						price = l_price;
					}
					if (l_price - price < 0) {
						price = l_price;
					}
				} else if (level_price.type == 2) {
					if (store.state.leveldata) {
						let l_price = accMul(store.state.leveldata.discount, data.sell_price) / 10
						if (price == 0) {
							price = l_price;
						}
						if (l_price - price < 0) {
							price = l_price;
						}
					} else {
						return 0
					}
				}
			}
		}
		return Number(price).toFixed(2)
	} else {
		return 0
	}
}
export const getBrowser = () => {
	let ua = navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == "micromessenger") {
		return "微信";
	}
	return "其他";
};
export const getTheme = () => {
	Vue.prototype.skin = `
				--main-color:#ff3c29;
				--content-color:#fcedeb;
			`
}
export const getShowType = () => {
	let SystemInfo = store.state.SystemInfo;
	if(SystemInfo&&SystemInfo.model){
		if (SystemInfo.model.indexOf('iPhone X') > -1 || SystemInfo.model.indexOf('iPhone12') > -1 || SystemInfo.model
			.indexOf('iPhone13') > -1 || SystemInfo.model.indexOf('iPhone 11') > -1) {
			return true
		} else {
			return false
		}
	}else{
		return false
	}
	
}
module.exports = {
	wxPublicPay: wxPublicPay,
	formatTime: formatTime,
	getQueryVariable: getQueryVariable,
	compressimg: compressimg,
	toSaveImage: toSaveImage,
	getstatustext: getstatustext,
	Subtr: Subtr,
	getCookie: getCookie,
	judgeLogin: judgeLogin,
	uniCopy: uniCopy,
	onInput: onInput,
	getimgurl: getimgurl,
	changeloading: changeloading,
	decodeUnicode: decodeUnicode,
	accAdd: accAdd,
	getprice: getprice,
	getminprice: getminprice,
	geturl: geturl,
	getBrowser: getBrowser,
	getTheme: getTheme,
	getShowType: getShowType,
}
